package com.eps.dao;

import com.eps.core.EpsManager;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * User: Red_Code
 * Date: 12-10-29
 * Time: 下午5:30
 */
public class daobase implements daointerface {

    public void save(Object obj) throws Exception {
        Session session = EpsManager.getManager().getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(obj);
            tx.commit();
        } catch (Exception e) {
            if (null != tx) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
    }

    public void delete(Class cls, long id) {
        Object obj = find(cls, id);
        Session session = EpsManager.getManager().getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.delete(obj);
            tx.commit();
        } catch (Exception e) {
            if (null != tx) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
    }

    public Object find(Class cls, long id) {
        Object obj=null;
        Session session = EpsManager.getManager().getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            obj=session.get(cls,id);
            tx.commit();
        } catch (Exception e) {
            if (null != tx) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return obj;
    }

    public List findAll(Class cls) {
        List list=findByHQL(" from "+cls.getName());
        return list;
    }

    public List findByHQL(String hql) {
        List list = null;
        Session session = EpsManager.getManager().getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            list=session.createQuery(hql).list();
            tx.commit();
        } catch (Exception e) {
            if (null != tx) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return list;
    }

    public void update(Object obj) {
        Session session = EpsManager.getManager().getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(obj);
            tx.commit();
        } catch (Exception e) {
            if (null != tx) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
    }
}
